import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
	state:{
		taskList:localStorage.getItem("taskList")?JSON.parse(localStorage.getItem("taskList")):[]
	},
	getters:{
		isAll(state,_this){
			return state.taskList.length>0 && state.taskList.length === _this.overNum;
		},
		overNum(state){
			return state.taskList.reduce(function(sum,item){
				if(item.isChecked) sum+=1;
				return sum;
			},0)
		}
	},
	mutations:{
		// 根据ID删除
		DEL_TASK_BY_ID(state,id){
			if(window.confirm("确定要删除该信息吗")){
				state.taskList = state.taskList.filter(v=>v.id !== id);
			}

		},
		// 清除已完成任务
		CLEAR_OVER_TASKLIST(state){
			state.taskList = state.taskList.filter(v=>!v.isChecked);
		},
		ALL_HANDLER(state){
			// console.log(state,this.getters.isAll)
			const isAll = !this.getters.isAll;
			state.taskList = state.taskList.map(item=>{
				item.isChecked = isAll;
				return item;
			})
		},
		UP_IS_CHECKED_BY_ID(state,id){
			state.taskList = state.taskList.map(item=>{
				if(item.id === id) item.isChecked = !item.isChecked;
				return item;
			})
		},
		ADD_TASK_LIST(state,event){
			const title = event.target.value.trim();
			if(!title){
				alert("请输入任务标题！");
				return;
			}
			if(state.taskList.some(v=>v.title===title)){
				alert("任务的标题不允许重复");
				return;
			}
			state.taskList = [
				{
					id:Math.random().toString(36).slice(2),
					title,
					isChecked:true
				},
				...state.taskList
			];
			event.target.value = null;
		}
	}
});
export default store;